<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司id" prop="comId">
        <el-input
          v-model="queryParams.comId"
          placeholder="请输入公司id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['contractTemplate:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['contractTemplate:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['contractTemplate:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['contractTemplate:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板ID" align="center" prop="id" />
      <el-table-column label="模板名称" align="center" prop="name" />
      <el-table-column label="文件类型" align="center" prop="fileType" />
      <el-table-column label="存储路径" align="center" prop="filePath" />
<!--      <el-table-column label="模板变量" align="center" prop="variables" />-->
      <el-table-column label="公司id" align="center" prop="comId" />
      <el-table-column label="模板文件" align="center" prop="file" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['contractTemplate:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['contractTemplate:template:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDownload(scope.row)"
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入模板名称" />
            </el-form-item>
          <el-table-column label="模板ID" align="center" prop="id" />
            <el-form-item label="文件类型" prop="fileType">
              <el-input v-model="form.fileType" placeholder="请输入文件类型" />
            </el-form-item>
            <el-form-item label="存储路径" prop="filePath">
              <el-input v-model="form.filePath" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="文件名" prop="variables">
              <el-input v-model="form.variables" placeholder="请输入模板变量" />
            </el-form-item>
            <el-form-item label="公司id" prop="comId">
              <el-input v-model="form.comId" placeholder="请输入公司id" />
            </el-form-item>
          <!--文件上传字段-->
          <el-form-item label="上传文件" >
            <!--这里上传成功后会绑定文件名到form.fileName字段传给后端的新增接口，uploadBookFile定义上传请求， :before-upload是上传前的回调，用于文件格式校验 -->
            <el-upload
              class="upload-demo"
              action="#"
              :http-request="uploadFile"
              :drag="true"
              :before-upload="uploadFileFun"
              :headers="upload.headers"
              :file-list="form.fileList">
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip fontSize12 colorRed" slot="tip">上传文件格式为word或pdf或者txt，文件大小在2M以内</div>
            </el-upload>
          </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate,uploadTemplateFile } from "@/api/contractTemplate/template";
import {getToken} from "@/utils/auth";

export default {
  name: "Template",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        fileType: null,
        filePath: null,
        variables: null,
        comId: null,
        file: null  // 用于存储上传的文件
      },
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        // name: [
        //   { required: true, message: "模板名称不能为空", trigger: "blur" }
        // ],
        fileType: [
          { required: true, message: "文件类型不能为空", trigger: "change" }
        ],
        // filePath: [
        //   { required: true, message: "存储路径不能为空", trigger: "blur" }
        // ],
        comId: [
          { required: true, message: "公司id不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询合同模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        fileType: null,
        filePath: null,
        variables: null,
        createTime: null,
        comId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //文件上传前的校验
    uploadFileFun(file){
      var test = /(doc|docx|pdf|txt)$/.test(file.name.split('.').pop().toLowerCase());
      if (!test) {
        this.$message.error("请上传正确的文档格式!");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
        return false;
      }
    },
    //这里就是上传功能向后端发送上传请求，参数是一个二进制文件
    uploadFile(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      uploadTemplateFile(formData).then(res => {
        this.$message.success("上传成功");
        // 自动用原始文件名作为模板名称
        this.form.name = res.originalFilename.split('.')[0]; // 去掉后缀
        this.form.filePath = res.fileName; // 存储路径
      }).catch(err => {
        this.$message.error("上传失败: " + err.message);
      });
    },
    handleDownload(row){
      // var name = row.fileName;
      var url = row.filePath;
      this.$download.resource(url,false)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同模板编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('contractTemplate/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
